// -----------------------------
// Author: 		Dhaenens Gert	
// Creation: 	8/4/2013 8:58:27 PM				
// -----------------------------

#include "LuaStackDump.h"
#include "Lua.h"
#include "LuaIncl.h"

#include <fstream>
#include <sstream>

namespace ObjectLua
{

	Lua* LuaStackDump::s_lpLua = nullptr;

	LuaStackDump::LuaStackDump()
		: LuaObject(s_lpLua)
	{
	}
	
	LuaStackDump::LuaStackDump(const LuaStackDump& refLuaStackDump)
		: LuaObject(refLuaStackDump.m_lpLua)
	{
	}

	LuaStackDump& LuaStackDump::operator=(const LuaStackDump& refLuaStackDump)
	{
		m_lpLua = refLuaStackDump.m_lpLua;
		return (*this);
	}

	LuaStackDump::~LuaStackDump()
	{
	}

	void LuaStackDump::toFile(const char* lpFilePath)
	{
		std::ofstream stream;
		stream.open(lpFilePath);

		int stackSize = lua_gettop(m_lpLua->getState());
		for(int idx = 1; idx <= stackSize; ++idx)
		{
			std::stringstream line;

			int typeID = lua_type(m_lpLua->getState(),idx);
			switch(typeID)
			{
			case LUA_TSTRING:
				{
					std::string value = std::string(lua_tostring(m_lpLua->getState(),idx));
					line << idx << ":\tString (" << value.length() << ")\t\t\t- " << value;
					break;
				}
			case LUA_TTABLE:
				{
					line << idx << ":\tTable\t\t\t\t- ???";
					break;
				}
			case LUA_TNUMBER:
				{
					double nr = lua_tonumber(m_lpLua->getState(), idx);
					line << idx << ":\tNumber\t\t\t" << nr;
					break;
				}
			default:
				{
					line << idx << ":\t" << lua_typename(m_lpLua->getState(),typeID) << "\t\t\t- ???";
					break;
				}
			}

			stream << line.str() << "\n";
		}
		stream.close();
	}

}